/**
 * Copyright © 2015 eqxiu.com 北京中网易企秀科技有限公司 All rights reserved.
 */
package com.eqxiu.ieditor.api.controller.file;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.eqxiu.ieditor.api.controller.BaseApiController;
import com.eqxiu.ieditor.api.controller.file.doc.FileDoc;
import com.eqxiu.ieditor.commons.web.ResultData;
import com.eqxiu.ieditor.interceptor.UserContext;
import com.eqxiu.store.service.api.FileServiceApi;
import com.eqxiu.store.service.api.FileTagServiceApi;
import com.eqxiu.store.service.api.StorServiceApi;
import com.eqxiu.store.service.dto.FileDTO;
import com.eqxiu.store.service.dto.UpPolicyDTO;

/**
 * @description 文件上傳相關
 * @author ranger
 * @date Jun 1, 2017
 */
@RestController
public class FileController implements FileDoc, BaseApiController {

    @Autowired
    private FileServiceApi fileServiceApi;

    @Autowired
    private FileTagServiceApi fileTagServiceApi;

    @Autowired
    private StorServiceApi storServiceApi;

    @Autowired
    private Environment env;

    @Value("${qiniu.image.bucket}")
    private String bucket;

    private final String prefix = "ie/xst";

    @GetMapping("/api/m/upload/uptoken")
    public ResultData getUptoken(@RequestParam(required = false, defaultValue = "image") String mediaType) {
        String bucket = env.getProperty("qiniu." + mediaType + ".bucket", "eqxiu");
        String mimeLimit = env.getProperty("qiniu." + mediaType + ".mimeLimit", "image/png;image/jpeg");
        UpPolicyDTO policyDTO = new UpPolicyDTO();
        policyDTO.setMimeLimit(mimeLimit);
        return success().setObj(storServiceApi.getUptokenWithPolicy(bucket, 3600, policyDTO));
    }

    @PostMapping("/api/m/upload/save")
    public ResultData save(HttpServletRequest request) {
        String userId = UserContext.getUser().getId();
        FileDTO fileInfo = new FileDTO();
        long size = 0L;
        String sizeStr = request.getParameter("size");
        if (sizeStr != null) {
            size = Long.parseLong(sizeStr);
        }
        String key = request.getParameter("path");
        String name = request.getParameter("name");
        String tmbPath = request.getParameter("tmbPath");
        Integer bizType = Integer.parseInt(request.getParameter("bizType"));
        Integer fileType = Integer.parseInt(request.getParameter("fileType"));
        fileInfo.setName(name);
        fileInfo.setPath(key);
        fileInfo.setFileType(fileType);
        fileInfo.setExtName(name != null ? name.substring(name.indexOf(".")) : "");
        fileInfo.setSize(size);
        fileInfo.setBizType(bizType);
        fileInfo.setCreateUser(userId);
        fileInfo.setTmbPath(tmbPath);
        if (request.getParameter("libType") != null) {
            int libtype = Integer.parseInt(request.getParameter("libType"));
            fileInfo.setLibType(libtype);
        }
        fileInfo = fileServiceApi.saveFile(fileInfo);
        String tagId = request.getParameter("tagId");
        if (tagId != null && !"0".equals(tagId)) {
            List<Long> fileIds = new ArrayList<Long>(1);
            fileIds.add(fileInfo.getId());
            if (tagId.matches("[0-9]+")) {
                fileTagServiceApi.batchSetFileTag(Long.valueOf(tagId), fileIds, fileInfo.getCreateUser());
            }
        }
        return success().setObj(fileInfo);
    }

    @PostMapping("/api/upload/fetch")
    public ResultData fetch(@RequestParam String remoteURL) {
        try {
            URL url = new URL(remoteURL);
            String saveasKey = prefix + url.getPath();
            storServiceApi.fetch(bucket, remoteURL, saveasKey);
            return success().setObj(saveasKey);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return fail().setMsg(e.getMessage());
        }
    }

}
